<template>
    <div class="register-wrapper" :class="{ 'dark-mode': isDark }">
        <!-- 标题 -->
        <div class="header">
            <h2>注册新用户</h2>
            <p>欢迎注册本平台，请在下方填写相关信息</p>
        </div>

        <!-- 注册表单 -->
        <el-form :model="form" :rules="rule" ref="formRef" class="form">
            <el-form-item prop="username">
                <el-input
                        v-model="form.username"
                        maxlength="20"
                        type="text"
                        placeholder="用户名"
                        clearable
                        :prefix-icon="User"
                />
            </el-form-item>

            <el-form-item prop="password">
                <el-input
                        v-model="form.password"
                        maxlength="20"
                        type="password"
                        placeholder="密码"
                        clearable
                        show-password
                        :prefix-icon="Lock"
                />
            </el-form-item>

            <el-form-item prop="password_repeat">
                <el-input
                        v-model="form.password_repeat"
                        maxlength="20"
                        type="password"
                        placeholder="重复密码"
                        clearable
                        show-password
                        :prefix-icon="Lock"
                />
            </el-form-item>

            <el-form-item prop="email">
                <el-input
                        v-model="form.email"
                        type="email"
                        placeholder="电子邮件地址"
                        clearable
                        :prefix-icon="Message"
                />
            </el-form-item>

            <el-form-item prop="code">
                <div class="code-row">
                    <el-input
                            v-model="form.code"
                            maxlength="6"
                            type="text"
                            placeholder="请输入验证码"
                            clearable
                            :prefix-icon="Edit"
                    />
                    <el-button
                            type="success"
                            :disabled="!isEmailValid || coldTime"
                            @click="askCode"
                    >
                        {{ coldTime > 0 ? `请稍后${coldTime}秒` : '获取验证码' }}
                    </el-button>
                </div>
            </el-form-item>
        </el-form>

        <!-- 注册按钮 -->
        <el-button class="register-btn" type="warning" plain @click="register()">
            立即注册
        </el-button>

        <!-- 登录链接 -->
        <div class="login-link">
            <span>已有账号?</span>
            <el-link @click="router.push('/')" class="login-link-text">立即登录</el-link>
        </div>
    </div>
</template>

<script setup>
import {computed, reactive, ref} from 'vue'
import {Edit, Lock, Message, User} from '@element-plus/icons-vue'
import router from '@/router/index.js'
import {get, post} from '@/net/index.js'
import {ElMessage} from 'element-plus'
import {useDark} from '@vueuse/core'

const isDark = useDark()

const form = reactive({
    username: '',
    password: '',
    password_repeat: '',
    email: '',
    code: ''
})

const validateUsername = (rule, value, callback) => {
    if (!value) callback(new Error('请输入用户名'))
    else if (!/^[a-zA-Z0-9一-龥]+$/.test(value))
        callback(new Error('用户名不能包含特殊字符，只能是中文/英文/数字'))
    else callback()
}

const validatePassword = (rule, value, callback) => {
    if (!value) callback(new Error('请再次输入密码'))
    else if (value !== form.password) callback(new Error('两次输入的密码不一致'))
    else callback()
}

const rule = {
    username: [
        {validator: validateUsername, trigger: ['blur', 'change']},
        {min: 2, max: 20, message: '用户名长度必须在2-20字符之间', trigger: ['blur', 'change']}
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 6, max: 20, message: '密码长度必须在6-20字符之间', trigger: ['blur', 'change']}
    ],
    password_repeat: [{validator: validatePassword, trigger: ['blur', 'change']}],
    email: [
        {required: true, message: '请输入邮箱地址', trigger: 'blur'},
        {type: 'email', message: '请输入合法邮箱地址', trigger: ['blur', 'change']}
    ],
    code: [{required: true, message: '请输入验证码', trigger: 'blur'}]
}

const coldTime = ref(0)
const timer = ref(null)
const formRef = ref()

const isEmailValid = computed(() => /^[\w.-]+@[\w.-]+\.\w+$/.test(form.email))

function askCode() {
    if (!isEmailValid.value) return ElMessage.warning('请输入正确的电子邮件')
    coldTime.value = 60
    if (timer.value) clearInterval(timer.value)

    get(`/api/auth/ask-code?email=${form.email}&type=register`, () => {
        ElMessage.success(`验证码已发送到邮箱: ${form.email}`)
        timer.value = setInterval(() => {
            coldTime.value--
            if (coldTime.value <= 0) {
                clearInterval(timer.value)
                timer.value = null
            }
        }, 1000)
    }, (err) => {
        ElMessage.warning(err)
        coldTime.value = 0
    })
}

function register() {
    formRef.value.validate(valid => {
        if (!valid) return ElMessage.warning('请完整填写注册信息')
        post('/api/auth/register', {...form}, () => {
            ElMessage.success('注册成功，欢迎加入我们')
            router.push('/')
        }, (msg) => {
            ElMessage.error(msg)
        })
    })
}
</script>

<style scoped>
.register-wrapper {
    max-width: 340px;
    margin: 0 auto;
    padding: 1.25rem 1rem;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 100%;
    user-select: none;
    transition: background-color 0.3s, color 0.3s;
}

.header {
    text-align: center;
    margin-bottom: 1.5rem;
}

.header h2 {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
}

.header p {
    font-size: 0.875rem;
    color: var(--el-text-color-secondary);
}

.form {
    display: flex;
    flex-direction: column;
    gap: 0.375rem;
}

::v-deep(.el-input__wrapper) {
    border-radius: 0.625rem;
    height: 2.625rem;
    font-size: 0.875rem;
}

::v-deep(.el-form-item) {
    margin-bottom: 0.7rem;
}

.code-row {
    display: flex;
    align-items: center;
    gap: 0.625rem;
    width: 100%;
}

::v-deep(.code-row .el-button) {
    width: 8.125rem;
    flex-shrink: 0;
    height: 2.625rem;
    border-radius: 0.625rem;
}

.register-btn {
    margin-top: 1.5rem;
    width: 100%;
    height: 2.625rem;
    border-radius: 0.625rem;
    font-size: 1rem;
}

.login-link {
    margin-top: 1rem;
    text-align: center;
}

.login-link span {
    font-size: 0.875rem;
    color: var(--el-text-color-secondary);
}

.login-link-text {
    margin-left: 0.25rem;
    color: var(--el-color-primary);
    cursor: pointer;
    transition: color 0.3s;
}

/* 深色模式 */
.dark-mode {
    background-color: #181818;
    color: #e5e5e5;
}

.dark-mode .header p,
.dark-mode .login-link span {
    color: #aaa;
}

.dark-mode ::v-deep(.el-input__wrapper) {
    background-color: #2a2a2a;
    border-color: #444;
    box-shadow: inset 0 0 0 1px #444;
}

.dark-mode ::v-deep(.el-input__inner) {
    color: #f0f0f0;
}

.dark-mode .login-link-text {
    color: #66b1ff;
}

.dark-mode .login-link-text:hover {
    color: #409eff;
}
</style>